package com.abc.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.xxx.dao.DeptMapper;
import com.abc.xxx.model.Dept;
import com.abc.xxx.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Override
    public boolean hasChildrenDepts(Integer deptId) {
        QueryWrapper<Dept> w = new QueryWrapper<>();
        w.eq("parent",deptId);
        return retBool(count(w));
    }

    @Override
    public List<Dept> findDescendantNodes(Integer deptId) {
        Objects.requireNonNull(deptId, "部门id不能为空");
        QueryWrapper<Dept> w = new QueryWrapper<>();
        // 假如deptId是一个顶级部门（5），
        // 它的子级别部门的parents字段是这样：: “0,5,”
        // 它的孙级别部门的parents字段是这样：: “0,5,6,”
        // 由于顶级一定是0，即： “0,5,6,”
        // 所以匹配规则是：“,5,”
        String likeStr;
        likeStr = String.format(",%d,", deptId);
        w.like("parents", likeStr);
        log.info("查询子孙节点的部门, 匹配字符串：{}", likeStr);
        return list(w);
    }

}
